// index.vue
<script setup>
	import {
		ref,
		computed,
		onMounted
	} from 'vue'
	import {
		useUserStore
	} from '@/stores/modules/user'
	import {
		useDeviceStore
	} from '@/stores/modules/device'
	import {
		system
	} from '@/utils/system'
	import {
		storage
	} from '@/utils/storage'

	const userStore = useUserStore()
	const deviceStore = useDeviceStore()

	// 状态栏高度
	const statusBarHeight = system.getStatusBarHeight()

	// 用户信息
	const userInfo = computed(() => userStore.userInfo)

	// 当前日期
	const currentDate = computed(() => {
		const date = new Date()
		return `${date.getFullYear()} 年 ${date.getMonth() + 1} 月 ${date.getDate()} 日`
	})

	// 底部标签配置
	const tabs = [{
			text: '对话',
			icon: 'icon-message'
		},
		{
			text: '发现',
			icon: 'icon-search'
		},
		{
			text: '创建',
			icon: 'icon-add'
		},
		{
			text: '通知',
			icon: 'icon-notification'
		},
		{
			text: '我的',
			icon: 'icon-user'
		}
	]
	const currentTab = ref(0)

	// 设备列表数据
	const deviceList = computed(() => deviceStore.privateDevices || [])
	const recommendDevice = computed(() => {
		const publicDevices = deviceStore.publicDevices || []
		return publicDevices[0] || null
	})
	const loading = ref(false)
	const refreshing = ref(false)

	// 检查登录状态
	const checkLogin = async () => {
		if (!userStore.checkLoginStatus()) {
			uni.redirectTo({
				url: '/pages/login/login'
			})
			return false
		}
		// 确保用户信息存在
		if (!userStore.userInfo) {
			try {
				await userStore.getUserInfo()
			} catch (error) {
				console.error('获取用户信息失败:', error)
				uni.redirectTo({
					url: '/pages/login/login'
				})
				return false
			}
		}
		return true
	}

	// 加载数据
	const loadData = async () => {
		if (loading.value) return
		loading.value = true

		try {
			// 先检查登录状态
			if (!await checkLogin()) return

			// 加载设备列表
			await Promise.all([
				deviceStore.loadPrivateDevices(),
				deviceStore.loadPublicDevices({
					current: 1,
					size: 10
				})
			])
		} catch (error) {
			console.error('加载失败:', error)

			if (error.message?.includes('登录')) {
				uni.redirectTo({
					url: '/pages/login/login'
				})
			} else {
				uni.showToast({
					title: error.message || '加载失败',
					icon: 'none'
				})
			}
		} finally {
			loading.value = false
		}
	}
	// 下拉刷新
	const refresh = async () => {
		refreshing.value = true
		await loadData()
		refreshing.value = false
		uni.stopPullDownRefresh()
	}

	// 加载更多
	const loadMore = async () => {
		if (loading.value || !checkLogin()) return
		loading.value = true

		try {
			const currentPage = Math.ceil((deviceStore.publicDevices?.length || 0) / 10) + 1
			await deviceStore.loadPublicDevices({
				current: currentPage,
				size: 10
			})
		} catch (error) {
			console.error('加载更多失败:', error)
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			})
		} finally {
			loading.value = false
		}
	}

	// 切换标签页
	const switchTab = (index) => {
		const routes = [
			'/pages/index/index',
			'/pages/discover/discover',
			'/pages/create/create',
			'/pages/notification/notification',
			'/pages/my/my'
		]
		uni.switchTab({
			url: routes[index]
		})
	}
	const gotoChat = (device) => {
		if (checkLogin()) {
			console.log('跳转到聊天页面,设备ID:', device.id)
			uni.navigateTo({
				url: `/pages/chat/chat?id=${device.id}`
			})
		}
	}

	// 在页面加载时检查登录并加载数据
	onMounted(() => {
		if (checkLogin()) {
			loadData()
		}
	})
</script>


<template>
	<view class="index-container">
		<!-- 顶部导航 -->
		<view class="nav-bar" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="title">对话</view>
			<view class="add-btn" @tap="gotoCreate">
				<text class="iconfont icon-plus" />
			</view>
		</view>

		<!-- AI列表 -->
		<scroll-view class="chat-list" scroll-y @scrolltolower="loadMore" refresher-enabled @refresherrefresh="refresh">
			<view v-for="item in deviceList" :key="item.id" class="device-item" @tap="gotoChat(item)">
				<view class="action">
					<image class="avatar" :src="item.icon || '/static/avatar.jpg'" mode="aspectFill" />
				</view>

				<view class="content">
					<view class="title-row">
						<text class="name">{{ item.name }}</text>
						<text class="tag" v-if="item.tag">{{ item.tag }}</text>
					</view>
					<text class="desc">{{ item.description }}</text>
				</view>
			</view> <!-- 这里是device-item的结束标签 -->

		</scroll-view>

		<!-- 底部导航 -->
		<view class="tab-bar">
			<view v-for="(tab, index) in tabs" :key="index" class="tab-item" :class="{ active: currentTab === index }"
				@tap="switchTab(index)">
				<text class="iconfont" :class="tab.icon" />
				<text class="text">{{ tab.text }}</text>
			</view>
		</view>
	</view>
</template>

<style lang="scss">
	.index-container {
		min-height: 100vh;
		background: #fff;

		// 顶部导航
		.nav-bar {
			height: 88rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 30rpx;
			border-bottom: 1px solid #f5f5f5;
			background: #fff;

			.title {
				font-size: 36rpx;
				font-weight: 600;
				color: #333;
			}

			.add-btn {
				width: 44rpx;
				height: 44rpx;
				display: flex;
				align-items: center;
				justify-content: center;

				.iconfont {
					font-size: 44rpx;
					color: #333;
				}
			}
		}

		// 聊天列表
		.chat-list {
			padding: 0;

			.device-item {
				padding: 24rpx 30rpx;
				display: flex;
				align-items: flex-start; // 改为 flex-start 更好的对齐效果
				border-bottom: 1px solid #F5F5F5;
				background: #fff;

				.action {
					flex-shrink: 0;
					margin-right: 20rpx;

					.avatar {
						width: 100rpx;
						height: 100rpx;
						border-radius: 12rpx;
					}
				}

				.content {
					flex: 1;
					min-width: 0; // 确保文字溢出样式生效
					margin-top: 4rpx; // 稍微下移以对齐头像

					.title-row {
						margin-bottom: 12rpx;
						display: flex;
						align-items: center;

						.name {
							flex: 1;
							font-size: 32rpx;
							font-weight: 500;
							color: #333;
							overflow: hidden;
							text-overflow: ellipsis;
							white-space: nowrap;
						}
					}

					.desc {
						font-size: 26rpx;
						color: #999;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
						line-height: 1.4;
					}
				}
			}
		}

		// 底部导航
		.tab-bar {
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
			height: 110rpx;
			background: #fff;
			display: flex;
			align-items: center;
			border-top: 1rpx solid #eee;
			padding-bottom: env(safe-area-inset-bottom);

			.tab-item {
				flex: 1;
				display: flex;
				flex-direction: column;
				align-items: center;
				color: #999;

				.iconfont {
					font-size: 48rpx;
					margin-bottom: 6rpx;
				}

				.text {
					font-size: 24rpx;
				}

				&.active {
					color: #007AFF;
				}
			}
		}
	}
</style>